<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding: 0;
        }
        .box{
            margin: 10px;
        }
        .progressBox{
            width: 300px;
            height:50px;
            border:1px solid #ccc;
            background-color: #eeeeee;
        }
        .progressInner{
            width: 0px;
            height:50px;
            line-height: 50px;
            background-color: #0187fb;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="box">

        <div class="progressBox">
            <div class="progressInner">0%</div>
        </div>
        <br>
        <div>
            <button id="install">安装</button>
            &nbsp;
            <button id="init">重置</button>
        </div>
        
    </div>

   <script>
    // 安装按钮
    let install = document.getElementById('install')
    // 重置按钮
    let init = document.getElementById('init')
    // 进度条盒子
    let progressBox = document.getElementsByClassName('progressBox')[0]
    // 进度条
    let progressInner = document.getElementsByClassName('progressInner')[0]
    
    // 进度条百分比
    let rate_of_progress = 0
    // 初始化进度条
    progressInner.innerHTML = `${rate_of_progress}%`
    // 定时器
    let time = null

    function addRate() {  
            // 获取总进度条长度
            let widthDOM = progressBox.clientWidth

            time = setInterval(()=>{
            // 进度条加载的数值
            rate_of_progress += Math.random()*20
            // 小于100%
            if(rate_of_progress < 100){
            // 进度条数值
            progressInner.innerText = `${rate_of_progress.toFixed(2)}%`
            // 进度条安装进度
            progressInner.style.width = (widthDOM * rate_of_progress/100)+'px'
    
            return  
            }

            // 安装完成
            progressInner.style.width = widthDOM + 'px'
            progressInner.innerText = '100%'
            // 提示 此处需要使用定时器让alert变成异步，否则弹框的进程比渲染DOM快
            setTimeout(()=>{
                alert('安装完成')
            },10)
            // 清除定时器
            clearInterval(time)
            },1000)  

        }
  
    // 安装
    install.addEventListener('click',()=>{
        addRate()
    })
    // 重置
    init.addEventListener('click',()=>{
            clearInterval(time)
            rate_of_progress = 0
            progressInner.style.width = 0 + 'px'
            progressInner.innerText = '0%'
    })


   </script>
 
</body>
</html>